<template>
  <div class="student-management-container">
    <!-- 搜索和操作区域 -->
    <div class="search-action-container">
      <el-card shadow="never">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="名称查询">
            <el-input
              v-model="form.studentName"
              placeholder="请输入学生姓名"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="学号查询">
            <el-input
              v-model="form.num"
              placeholder="请输入学生学号"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item label="班级查询">
            <el-input
              v-model="form.className"
              placeholder="请输入学生班级"
              clearable
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              @click="getStudentList"
              icon="el-icon-search"
              >查询</el-button
            >
            <el-button @click="resetSearch" icon="el-icon-refresh"
              >重置</el-button
            >
          </el-form-item>
          <el-form-item class="add-student-btn">
            <el-button
              type="primary"
              @click="dialogVisible = true"
              icon="el-icon-plus"
              >添加学生</el-button
            >
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 数据表格区域 -->
    <div class="table-container">
      <el-card shadow="never">
        <el-table
          :data="tableData"
          style="width: 100%"
          stripe
          border
          v-loading="loading"
          element-loading-text="拼命加载中"
          element-loading-spinner="el-icon-loading"
          element-loading-background="rgba(0, 0, 0, 0.8)"
        >
          <el-table-column
            prop="studentId"
            label="编号"
            width="100"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="studentName"
            label="姓名"
            width="120"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="num"
            label="学号"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="className"
            label="班级"
            align="center"
          ></el-table-column>
          <el-table-column
            label="操作"
            width="180"
            align="center"
            fixed="right"
          >
            <template slot-scope="scope">
              <el-button
                @click="openEdit(scope.row)"
                type="primary"
                size="mini"
                icon="el-icon-edit"
                circle
              ></el-button>
              <el-button
                @click="deleteStudent(scope.row)"
                type="danger"
                size="mini"
                icon="el-icon-delete"
                circle
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </div>

    <!-- 添加学生对话框 -->
    <el-dialog
      title="添加学生"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <el-form ref="addForm" :model="addForm" label-width="80px" :rules="rules">
        <el-form-item label="姓名" prop="studentName">
          <el-input
            v-model="addForm.name"
            placeholder="请输入学生姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="学号" prop="num">
          <el-input
            v-model="addForm.num"
            placeholder="请输入学生学号"
          ></el-input>
        </el-form-item>
        <el-form-item label="班级" prop="className">
          <el-select
            v-model="addForm.classId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入学生班级"
            :remote-method="remoteMethod"
            :loading="loading"
          >
            <el-option
              v-for="item in classList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onClickAddStudent">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑学生对话框 -->
    <el-dialog
      title="编辑学生"
      :visible.sync="dialogEdit"
      width="500px"
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        label-width="80px"
        :rules="rules"
      >
        <el-form-item label="姓名" prop="studentName">
          <el-input
            v-model="editForm.name"
            placeholder="请输入学生姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="学号" prop="num">
          <el-input
            v-model="editForm.num"
            placeholder="请输入学生学号"
          ></el-input>
        </el-form-item>
        <el-form-item label="班级" prop="className">
          <el-select
            v-model="editForm.classId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入学生班级"
            :remote-method="remoteMethod"
            :loading="loading"
          >
            <el-option
              v-for="item in classList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogEdit = false">取 消</el-button>
        <el-button type="primary" @click="editStudent">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getStudentList,
  addStudent,
  editStudent,
  deleteStudent,
} from "@/api/student.js";

import { getClassList } from "@/api/class.js";

export default {
  data() {
    return {
      classList: [],
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      form: {
        name: "",
        num: "",
        className: "",
      },
      dialogVisible: false,
      addForm: {
        name: "",
        num: "",
        classId: "",
        className:"",
      },
      dialogEdit: false,
      editForm: {
        id: "",
        name: "",
        num: "",
        className: "",
      },
      rules: {
        name: [
          { required: true, message: "请输入姓名", trigger: "blur" },
          {
            min: 2,
            max: 10,
            message: "长度在 2 到 10 个字符",
            trigger: "blur",
          },
        ],
        num: [
          { required: true, message: "请输入学号", trigger: "blur" },
          { pattern: /^\d+$/, message: "学号必须为数字", trigger: "blur" },
        ],
      },
      options: [],
      value: [],
      list: [],
      loading: false,
    };
  },
  mounted() {
    this.getClassList();
    this.getStudentList();

  },
  methods: {
    remoteMethod(query) {
      this.getClassList(query);
    },
    getClassList(query) {
      getClassList({ name: query }).then((res) => {
        this.classList = res.rows;
        console.log(this.classList);
      });
    },
    getStudentList() {
      this.loading = true;
      getStudentList({
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        ...this.form,
      })
        .then((res) => {
          this.tableData = res.rows;
          this.total = res.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },

    resetSearch() {
      this.form = {
        name: "",
        num: "",
      };
      this.getStudentList();
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.getStudentList();
    },

    handleCurrentChange(val) {
      this.pageNum = val;
      this.getStudentList();
    },

    handleClose(done) {
      this.$confirm("确认关闭？关闭后表单数据将不被保存", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.resetForm();
          done();
        })
        .catch(() => {});
    },

    onClickAddStudent() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          addStudent({
            ...this.addForm,
          })
            .then((res) => {
              this.$message.success("添加成功");
              this.dialogVisible = false;
              this.resetForm("addForm");
              this.getStudentList();
            })
            .catch((error) => {
              this.$message.error("添加失败: " + error.message);
            });
        }
      });
    },

    // 数据回显（深拷贝）  
openEdit(row) {  
  this.dialogEdit = true;  
  this.editForm = {  
    ...row,  
    className: row.classId  // 明确字段转换逻辑  
  };  
},  

// 提交逻辑（含状态管理）  
editStudent() {  
  this.$refs.editForm.validate((valid) => {  
    if (valid) {  
      this.loading = true;  
      editStudent({  
        id: this.editForm.id,  
        name: this.editForm.name,  
        num: this.editForm.num,  
        classId: this.editForm.className  
      })  
      .then(() => {  
        this.$message.success("编辑成功");  
        this.dialogEdit = false;  
        this.$refs.editForm.resetFields();  
        this.getStudentList();  
      })  
      .catch(error => {  
        this.$message.error(`编辑失败: ${error.response?.data?.message || error.message}`);  
      })  
      .finally(() => {  
        this.loading = false;  
      });  
    }  
  });  
}  ,


    deleteStudent(row) {
      this.$confirm("此操作将永久删除该学生, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteStudent({
            id: row.studentId,
          })
            .then((res) => {
              this.$message.success("删除成功");
              this.getStudentList();
            })
            .catch((error) => {
              this.$message.error("删除失败: " + error.message);
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },

    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
    },
  },
};
</script>

<style scoped>
.student-management-container {
  padding: 20px;
  background-color: #f0f2f5;
}

.search-action-container {
  margin-bottom: 20px;
}

.search-action-container .el-form-item {
  margin-bottom: 0;
}

.search-action-container .add-student-btn {
  float: right;
  margin-right: 0;
}

.table-container {
  margin-bottom: 20px;
}

.pagination-container {
  text-align: center;
}

.el-table {
  margin-top: 20px;
}

.el-card {
  border-radius: 4px;
}

.el-button--mini.is-circle {
  padding: 7px;
}

.el-dialog__body {
  padding: 20px 30px;
}
</style>